﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;

namespace WAVE
{
    class Xbee
    {
        int packetLength = 0;
        long highAddress = 0;
        long lowAddress = 0;

        private long millis()
        {
            return 1000;
        }

        private Boolean getData(SerialPort Serial, byte _receivedData, uint timeOut)
        {
            uint timeout = timeOut;
            long startTime;
            byte inByte = 0;
            startTime = millis();
            while (inByte != 0x7E)
            {
                inByte = Convert.ToByte(Serial.ReadByte());
                if ((millis()-startTime) < timeout)
                    return false;
            }
            //look for start byte 0x7E(~)
	        if (inByte == 0x7E) {                               // if we got the API start byte
		        startTime = millis();
		        while (Serial.BytesToRead < 2){                     // block for length byte two bytes to be available
			        if((millis() - startTime) > timeout) 
				        return false;    // timed out bad message
		        }
            	    if (Serial.BytesToRead > 1){                        // if we got 2 bytes
			            int lengthMSB = Serial.ReadByte();                    // read the most significant length byte
			            int lengthLSB = Serial.ReadByte();                    // read the least significant length byte
			            packetLength = (lengthMSB << 8) + lengthLSB;      // put the two bytes together
		            }
	            }
            	
	            //***************
	            // if we have a packet continue get APIDENTIFIER
	            if (packetLength > 0) {
		            byte apiIdentifier = 0x5A;                                // set apiIdentifier to an impossible value ['Z']
		            startTime = millis();
		            while (Serial.BytesToRead < 1){                     // wait for a byte or timeout
			            if((millis() - startTime) > timeout)
				            return false;    // timed out bad message
		            }
            		
		            if (Serial.BytesToRead > 0) {                       // if a byte is waiting in the buffer set it to the API
			            apiIdentifier = Convert.ToByte(Serial.ReadByte());
		            } else 
			            return false; //else bad message
            		
		            //***************
		            //GET LONG ADDRESS
		            byte addrByte=0;
		            highAddress=0;                                      // clear out address
		            lowAddress=0;
		            startTime = millis();
		            while(Serial.BytesToRead < 8){                      // stop for bytes
			            if((millis() - startTime) > timeout) 
				            return false;     // timed out bad message
		            }
		            if (Serial.BytesToRead > 7) {
			            byte[] address;                                  // array for address
			            for (int i = 0; i< 8; i++){
				            addrByte = Convert.ToByte(Serial.ReadByte());
				            address[i] = addrByte;
            		
				            //global last send
				            if (i < 4){                                     // get first half of address
					            highAddress += (addrByte << ((3-i) * 8));       // get the first 4 bytes shift into place 4321
				            }
				            else {
					            lowAddress += (addrByte << ((7-i) * 8)); // get second shift them int place 4321
				            }
			            }
            		
		            }else  
			            return false;                                    // timed out bad message
            			
		            //***************
		            //GET LOCAL ADDRESS
		            startTime = millis();
		            while (Serial.BytesToRead < 2){                     // wait for at least two bytes to be available
			            if((millis() - startTime) > timeout) 
				            return false;      // timed out bad message
		            }
		            int localAd = Serial.ReadByte();                        // read the most significant length byte
		            int localAd2 = Serial.ReadByte();                       // read the least significant length byte
                    int localAddress;                                   // local address it was sent from
		            localAddress = (localAd << 8) + localAd2;           // put the two bytes together
            		
		            //***************
		            //GET OPTION
		            startTime = millis();
		            while (Serial.BytesToRead < 1){
			            if((millis() - startTime) > timeout) 
				            return false;      // timed out bad message
            		
		            }
                   
		            byte options = Convert.ToByte(Serial.ReadByte());                    // get the options 1 packet ack returned 2 broadcast
            		
		            //***************
		            //GET DATA
		            startTime = millis();
		            int dataLength = (packetLength - 12);						//record the length of incoming data
		            while (Serial.BytesToRead < (packetLength - 12)){
			            if((millis() - startTime) > timeout) 
				            return false;
		            }
            		
		            for (int i= 0; i < (packetLength - 12); i++) {			// take out other info in packet + checksum
                        byte[] _receivedData;
			            _receivedData [i] = Convert.ToByte(Serial.ReadByte());				// get a byte of data
		            }
            		
		            //***************
		            //GET CHECKSUM
		            startTime = millis();
		            while (Serial.BytesToRead < 1){
			            if((millis() - startTime) > timeout)
				            return false;          // timed out bad message
		            }
		            int checksum = Serial.ReadByte();
	            }
	            return true;                                               // if everything went well return a true
            }
                        
        }



        //static byte FrameID = 0x01;
        //const byte ATCommand = 0x09;
        //const byte Start = 0x7E;
        //public byte[] NDPacket = new byte[8];
        ////public byte[] onOffPacket = new byte[];

        //public void buildNodeDiscoveryPacket()
        //{
        //    FrameID++;
        //    if (FrameID == 0) FrameID = 1;
            
        //    NDPacket[0] = Start;        //Start
        //    NDPacket[1] = 0x00;         //Length 1
        //    NDPacket[2] = 0x04;         //Length 2
        //    NDPacket[3] = ATCommand;    //Command Type
        //    NDPacket[4] = FrameID;           //Command ID
        //    NDPacket[5] = (byte)'N';    //Send ND command
        //    NDPacket[6] = (byte)'D';    
        //    NDPacket[7] = generateCheckSum(NDPacket);//Generate a Checksum

        //    MessageBox.Show("Calling build Node Discovery Method");
        //}

        //public void buildOnOffPacket(byte[] destinationaddress64, byte[] destinationaddress16, bool OnOff)
        //{
        //    MessageBox.Show("build on off packet method is called.");
        //}

        //public byte generateCheckSum(byte[] packet)
        //{
        //    byte checksum; //this is the checksum value that will be returned for use in the outgoing packet
        //    byte sum = 0;

        //    for (int i = 3; i < packet.Length; i++)
        //        sum += packet[i];             //add the sum of the packets passed in

        //    checksum = (byte)((int)0xFF - (int)sum);//calculate the checksum = 0xFF - Sum

        //    MessageBox.Show("Calculating Checksum");
        //    return checksum;
        //}
    //}
}
